package gwt.trading.client;

import gwt.trading.client.geometry.Point;
import gwt.trading.client.util.Closure;
import gwt.trading.client.util.ColorEnum;
import gwt.trading.client.util.GwtList;

public class MovingAverage extends Indicator {

	public MovingAverage(StockQuoteList quotes) {
		super(quotes, ColorEnum.WHITE);
	}

	public String getId() {
		return ID;
	}

	public void draw(final Renderer renderer) {
		GwtList quotes = getQuoteList().getQuotes();
		
		// start line graph
		Point startPoint = transform((StockQuote) quotes.getFirst());
		renderer.startLine(startPoint, getColor());
		
		// intermediate lines
		quotes.forAllExceptEnds(new Closure() {

			public void execute(Object object) {
				Point next = transform((StockQuote) object);
				renderer.continueLine(next);
			}
		});
		
		// close line graph
		Point endPoint = transform((StockQuote) quotes.getLast());
		renderer.finishLine(endPoint);
	}

	private Point transform(StockQuote quote) {
		int index = quote.getIndex();
		float high = quote.getHigh();
		float low = quote.getLow();
		
		float sma = (high + low) / 2;
		
		int xPosition = getDrawingManager().getXPosition(index);
		int yPosition = getDrawingManager().getYPosition(sma);
		
		return new Point(xPosition, yPosition);
	}

	public static final String ID = "SMA";
}
